package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.CountDao;
import dao.StartDao;
import dao.UserDao;
import dao.impl.CountDaoImpl;
import dao.impl.StartDaoImpl;
import dao.impl.UserDaoImpl;
import moble.Admin;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// 设置编码为UTF-8
		request.setCharacterEncoding("utf-8");
		response.setHeader("Content-Type", "text/html; charset=utf-8");

		HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();

		// 登录
		String name = request.getParameter("username");
		String pwd = request.getParameter("password");
		Admin admin = new Admin();
		admin.setUserName(name);
		admin.setPassWord(pwd);
		UserDao ud = new UserDaoImpl();
		Admin sa = ud.loginUser(admin);

		// 首页统计各级车辆外租次数排行榜
		String[] type = { "A", "B", "C", "D" };
		StartDao sd = new StartDaoImpl();
		
		CountDao cd = new CountDaoImpl();
		
		ArrayList<Integer> li = new ArrayList<Integer>();
		if (sa != null) {

			session.setAttribute("admin", sa);

			for (int i = 0; i < type.length; i++) {
				int returnOrder = sd.selectOrderOne(type[i]);
				int returnOrderTwo = sd.selectOrderTwo(type[i]);
				int returnOrderThree = sd.selectOrderThree(type[i]);
				int returnOrderFour = sd.selectOrderFour(type[i]);
				li.add(returnOrder);
				li.add(returnOrderTwo);
				li.add(returnOrderThree);
				li.add(returnOrderFour);
				
				int returnMy = cd.selectMyCar(type[i]);
				int returnYou = cd.selectYouCar(type[i]);
				li.add(returnMy);
				li.add(returnYou);
			}
			session.setAttribute("li", li);
			request.getRequestDispatcher("index.jsp")
					.forward(request, response);
		} else {
			out.print("<script>alert('账号或密码不符!');location.href='login.jsp'</script>");
		}
	}

}
